﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using System.Xml;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Controls;

using PlanningGIS.Util.Convertor;
using PlanningGIS.ArcGIS;
using PlanningGIS.Util.Log;
using PlanningGIS.Engine.Controls;

namespace PlanningGIS.DataCheck.model
{
    /// <summary>
    /// 境界线属性异常检查（a，境界线的邻接界名不能为空并且格式应该正确；
    /// b ，检查境界线中的邻接界名属性是否与邻接境界面的名称属性对应；
    /// c，"如果境界线为省界，其邻接界名中必须包含'浙江省'）
    /// </summary>
    public class ADJNameExceptionCheck : Check
    {
        public int Check(string errType, IFeatureLayer pFeatLyrLn, IFeatureLayer pFeatLyrPy, IGeometry pGeometry, string whereClause,
            string fcodename, string fnamename, string adjnamename,double buffer)
        {

            IFeatureClass pFeatClsLn = pFeatLyrLn.FeatureClass;
            IFeatureClass pFeatClsPy = pFeatLyrPy.FeatureClass;

            int idxfcode = pFeatClsLn.FindField(fcodename);
            if (idxfcode == -1)
            {
               LogHelper.WriteErrLog("[" + pFeatLyrLn.Name + "]图层中未找到分类代码[" + fcodename + "]字段，检查失败！");
                return -1;
            }

            int idxadjname = pFeatClsLn.FindField(adjnamename);
            if (idxadjname == -1)
            {
               LogHelper.WriteErrLog("[" + pFeatLyrLn.Name + "]图层中未找到邻接界名[" + adjnamename + "]字段，检查失败！");
                return -1;
            }

            int idxfname = pFeatClsPy.FindField(fnamename);
            if (idxfname == -1)
            {
               LogHelper.WriteErrLog("[" + pFeatLyrPy.Name + "]图层中未找到名称[" + fnamename + "]字段，检查失败！");
                return -1;
            }

            if (pFeatClsLn.ShapeType != esriGeometryType.esriGeometryPolyline)
            {
               LogHelper.WriteErrLog("[" + pFeatLyrLn.Name + "]图层不是线状图层，检查失败！");
                return -1;
            }

            if (pFeatClsPy.ShapeType != esriGeometryType.esriGeometryPolygon)
            {
               LogHelper.WriteErrLog("[" + pFeatLyrPy.Name + "]图层不是面状图层，检查失败！");
                return -1;
            }

            ISpatialFilter pSpatialFileter = new SpatialFilterClass();
            if (pGeometry != null) pSpatialFileter.Geometry = pGeometry;

            string sql = fcodename + " in('620201376','630201376','640201376','650201376','660201376','670201376','680201376')";
            pSpatialFileter.WhereClause = whereClause == "" ? sql : whereClause + " and " + sql;

            pSpatialFileter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
            pSpatialFileter.GeometryField = pFeatClsLn.ShapeFieldName;

            showFakePro(true);
            LogHelper.WriteLog("正在计算需要检查的要素数目...");

            int max = FeatureClassHelper.GetFeatureCountFromLayer(pFeatLyrLn, pSpatialFileter);// pFeatClsLn.FeatureCount(pSpatialFileter);

            LogHelper.WriteLog("计算完毕。共有" + max + "个要素参与检查。");
            showFakePro(false);

            if (max == 0)
            {
                LogHelper.WriteLog("没有满足检查要求的要素存在。");
                return -1;
            }

            setProcessBarMax(max);

            IFeatureCursor pFeatCur;
            pFeatCur = pFeatLyrLn.Search(pSpatialFileter, false);

            IFeature pFeatureLn;

            int count = 0;
            int errCount = 0;

            while ((pFeatureLn = pFeatCur.NextFeature()) != null)
            {
                if (IsStop()) break;

                setProcessBarCurrent(count);
                count++;

                string adjnamevalue = StringHelper.ConvertWRTNull(pFeatureLn.get_Value(idxadjname));
                if (adjnamevalue.IndexOf('－') == -1)
                {
                    RecordListHelper.AddRecordItem(errType, pFeatLyrLn, pFeatLyrPy, pFeatureLn, null, pFeatureLn.ShapeCopy, "邻接界名格式不规范");
                    errCount++;
                    continue;
                }

                string fcodevalue = pFeatureLn.get_Value(idxfcode).ToString ();
                switch (fcodevalue)
                {
                    case "620201376"://已定界(国家行政区)
                        break;

                    case "630201376"://已定界(特别行政区)
                        break;

                    case "640201376"://已定界(省)
                        //省界应该都带有“浙江省”
                        if (adjnamevalue.IndexOf("浙江省") == -1)
                        {
                            RecordListHelper.AddRecordItem(errType, pFeatLyrLn, pFeatLyrPy, pFeatureLn, null, pFeatureLn.ShapeCopy, "省界邻接界名未带“浙江省”信息");
                            errCount++;
                            continue;
                        }

                        break;

                    case "650201376"://已定界(地区)
                        break;
                
                    case "660201376"://已定界(县)
                        break;
                
                    case "670201376"://已定界(乡镇)
                        break;
                
                    case "680201376"://已定界(自然保护区)
                        break;
                }

                //string adjnameleft = adjnamevalue.Split('－')[0];
                //string adjnameright = adjnamevalue.Split('－')[1];

                IGeometry pBuffer = GeometryHelper.GetBuffer(pFeatureLn.ShapeCopy, buffer);

                ISelectionSet pSelSetPy = CursorHelper.GetSelset(pFeatLyrPy as IFeatureSelection, pBuffer, "", esriSpatialRelEnum.esriSpatialRelIntersects);

                //如果通过该线找不到一个面，则认为是错误的
                if (pSelSetPy.Count == 0)
                {
                    RecordListHelper.AddRecordItem(errType, pFeatLyrLn, pFeatLyrPy, pFeatureLn, null, pFeatureLn.ShapeCopy, "未找到相应的境界面数据");
                    errCount++;
                    continue;
                }

                IEnumIDs pIDs = pSelSetPy.IDs;
                pIDs.Reset();
                int id ;

                int findcount = 0;

                while ((id = pIDs.Next())!=-1)
                {
                    IFeature pFeaturePy = pFeatClsPy.GetFeature(id);
                    string fnamevalue = StringHelper.ConvertWRTNull(pFeaturePy.get_Value(idxfname));
                    if (adjnamevalue.Contains(fnamevalue)) findcount++;
                }

                //如果一个符合条件的境界面都没找到或者只找到一个但相交的境界面不止一个的非省界线就认为错误.
                if(findcount ==0 || (findcount ==1 && pSelSetPy.Count !=findcount && fcodevalue !="640201376"))
                {
                    RecordListHelper.AddRecordItem(errType, pFeatLyrLn, pFeatLyrPy, pFeatureLn, null, pFeatureLn.ShapeCopy, "");
                    errCount++;
                }

                (pFeatLyrPy as IFeatureSelection).Clear();


            }

            finishPro.Invoke();

            DataCheckUtility.ReleaseComObject(pFeatureLn);
            DataCheckUtility.ReleaseComObject(pFeatCur);

            LogHelper.WriteLog("境界线属性异常检查结束。共发现" + errCount + "处错误！\n");

            return errCount;
        }


    }
}
